from pygoogletranslation import Translator
from libs.mypthon.textToAss import textToass_list

KEY_TEXT = 'Text'
KEY_BENGINTIME = 'BeginTime'
KEY_ENDTIME = 'EndTime'


# 由ass_list进行翻译,返回tr_ass_list列表
# bilingual 是否开启双语
def translate(ass_list, bilingual=False,targetLan="zh-CN"):
    '''
    由ass_list进行翻译,返回tr_ass_list列表
    bilingual 是否开启双语
    :param ass_list: list
    :param bilingual: bool
    :param targetLan:目标语言
    :return: bool,list
    '''
    # 获取列表
    ori_str_list = []
    for item in ass_list:
        ori_str_list.append(item[KEY_TEXT])
    # 为了科学上网,原来开源项目默认的google.com是访问不了的，要做下面修改
    translator = Translator()
    # try:
    t = translator.translate(ori_str_list, dest=targetLan)
    # 翻译好的列表,是否双语
    tra_str_list = []
    j = 0
    for item in t:
        if bilingual == False:
            tra_str_list.append(item.text)
        else:
            s=str('\\N')
            string = (ass_list[j][KEY_TEXT] + s + item.text )
            tra_str_list.append(string)
            j = j + 1
    # 加入时间
    ret_list = []
    i = 0
    for item_text in tra_str_list:
        item_time = ass_list[i]
        i = i + 1
        i_item = {KEY_TEXT: item_text, KEY_BENGINTIME: item_time[KEY_BENGINTIME], KEY_ENDTIME: item_time[KEY_ENDTIME]}
        ret_list.append(i_item)
            # print(item_text)
    # except  Exception as e:
    #     return False,e
    return True,ret_list


if __name__ == '__main__':
    asslist = textToass_list('F:/text.txt' )
    print(translate(asslist, True))
